<template>
  <div class="cabinet-list-container">
    <div class="content-wrapper">
      <page-header
        title="机柜管理"
        description="管理机房内的机柜设备，监控机柜的使用状态、电力负载、网络端口占用等信息。支持机柜的添加、编辑、删除，以及查看详细的设备部署情况。"
      >
        <el-input v-model="searchQuery" placeholder="搜索机柜..." class="search-input" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </page-header>

      <!-- 添加/编辑机柜对话框 -->
      <cabinet-form
        v-model:visible="dialogVisible"
        :cabinet-data="currentCabinet"
        @success="handleFormSuccess"
      />

      <div v-if="!currentRoom" class="no-room-tip">
        <el-empty description="请先配置机房">
          <el-button type="primary" @click="handleConfigRoom">去配置</el-button>
        </el-empty>
      </div>

      <template v-else>
        <!-- 机柜列表 -->
        <el-table
          v-loading="loading"
          :data="filteredCabinets"
          style="width: 100%"
          :height="tableHeight"
        >
          <el-table-column prop="cabinet_id" label="ID" width="80" fixed="left" />
          <el-table-column prop="cabinet_name" label="机柜名称" min-width="120" fixed="left">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleView(row)">
                {{ row.cabinet_name }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="manufacturer" label="制造商" width="120" />
          <el-table-column prop="model" label="型号" width="120" />
          <el-table-column label="机位使用" width="180">
            <template #default="{ row }">
              <el-tooltip
                :content="`${row.rack_units - row.available_units}/${row.rack_units}U`"
                placement="top"
              >
                <el-progress
                  :percentage="
                    Math.round(((row.rack_units - row.available_units) / row.rack_units) * 100)
                  "
                  :status="getUsageStatus(row.available_units, row.rack_units)"
                  :stroke-width="12"
                />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="电力使用" width="180">
            <template #default="{ row }">
              <el-tooltip :content="`${row.power_used}/${row.power_capacity}W`" placement="top">
                <el-progress
                  :percentage="Math.round((row.power_used / row.power_capacity) * 100)"
                  :status="getUsageStatus(row.power_capacity - row.power_used, row.power_capacity)"
                  :stroke-width="12"
                />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="网络端口" width="180">
            <template #default="{ row }">
              <el-tooltip
                :content="`${row.used_network_ports}/${row.network_ports}`"
                placement="top"
              >
                <el-progress
                  :percentage="Math.round((row.used_network_ports / row.network_ports) * 100)"
                  :status="
                    getUsageStatus(row.network_ports - row.used_network_ports, row.network_ports)
                  "
                  :stroke-width="12"
                />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="环境" width="160">
            <template #default="{ row }">
              <div class="environment-info">
                <el-tag size="small">
                  <el-icon class="el-icon--left"><Sunny /></el-icon>
                  {{ row.temperature }}°C
                </el-tag>
                <el-tag size="small" type="info">
                  <el-icon class="el-icon--left"><Umbrella /></el-icon>
                  {{ row.humidity }}%
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click.stop="handleView(row)">查看</el-button>
              <el-button type="primary" link @click.stop="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click.stop="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            :teleported="false"
            popper-class="pagination-select-dropdown"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </template>

      <floating-action-button tooltip="添加机柜" @click="handleAdd" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Search, Sunny, Umbrella } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoomConfigStore } from '@/store/roomConfigStore'
import CabinetForm from '@/components/asset/CabinetForm.vue'
import type { CabinetInfo } from '@/api/types'
import { assetService } from '@/api/assetService'
import PageHeader from '@/components/common/PageHeader.vue'
import FloatingActionButton from '@/components/common/FloatingActionButton.vue'

const router = useRouter()
const roomConfigStore = useRoomConfigStore()
const currentRoom = computed(() => roomConfigStore.currentRoom)

const loading = ref(false)
const cabinets = ref<CabinetInfo[]>([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const currentCabinet = ref<CabinetInfo>()
const tableHeight = ref(500)

// 过滤后的机柜列表
const filteredCabinets = computed(() => {
  if (!searchQuery.value) return cabinets.value
  const query = searchQuery.value.toLowerCase()
  return cabinets.value.filter(
    (cabinet) =>
      cabinet.cabinet_name.toLowerCase().includes(query) ||
      cabinet.manufacturer.toLowerCase().includes(query) ||
      cabinet.model.toLowerCase().includes(query),
  )
})

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case '正常':
      return 'success'
    case '异常':
      return 'danger'
    case '维护中':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取使用状态
const getUsageStatus = (available: number, total: number) => {
  const usagePercent = ((total - available) / total) * 100
  if (usagePercent >= 90) {
    return 'exception' // 红色
  }
  if (usagePercent >= 75) {
    return 'warning' // 黄色
  }
  return 'success' // 绿色
}

// 获取机柜列表
const fetchCabinets = async () => {
  if (!currentRoom.value) return
  loading.value = true
  try {
    const response = await assetService.getCabinets(currentRoom.value.room_id, {
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    cabinets.value = response.items
    total.value = response.total
  } catch (err) {
    console.error('获取机柜列表失败:', err)
    ElMessage.error('获取机柜列表失败')
  } finally {
    loading.value = false
  }
}

// 跳转到机房配置
const handleConfigRoom = () => {
  router.push('/settings/room-config')
}

// 监听当前机房变化
watch(currentRoom, () => {
  currentPage.value = 1
  fetchCabinets()
})

// 处理查看详情
const handleView = (cabinet: CabinetInfo) => {
  router.push(`/asset/cabinet/${cabinet.cabinet_id}`)
}

// 处理添加
const handleAdd = () => {
  currentCabinet.value = undefined
  dialogVisible.value = true
}

// 处理表单提交成功
const handleFormSuccess = () => {
  fetchCabinets() // 重新加载机柜列表
}

// 处理编辑
const handleEdit = (row: CabinetInfo) => {
  currentCabinet.value = row
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (cabinet: CabinetInfo) => {
  try {
    await ElMessageBox.confirm(`确认删除机柜 ${cabinet.cabinet_name}？`, '提示', {
      type: 'warning',
    })
    // TODO: 实现删除机柜的 API
    // await assetService.deleteCabinet(cabinet.cabinet_id)
    ElMessage.success('删除成功')
    fetchCabinets()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除机柜失败:', error)
      ElMessage.error('删除机柜失败')
    }
  }
}

// 处理分页
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchCabinets()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchCabinets()
}

// 计算表格高度
const updateTableHeight = () => {
  const vh = window.innerHeight
  tableHeight.value = vh - 64 - 48 - 52 - 32 - 24
}

// 监听窗口大小变化
onMounted(() => {
  updateTableHeight()
  window.addEventListener('resize', updateTableHeight)
  fetchCabinets()
})

onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight)
})
</script>

<style scoped lang="scss">
.cabinet-list-container {
  height: 100%;

  .content-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    padding-bottom: 48px;

    .no-room-tip {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 400px;
    }

    .environment-info {
      display: flex;
      gap: 8px;
      align-items: center;

      :deep(.el-tag) {
        display: inline-flex;
        align-items: center;
        line-height: 1;
        padding: 0 8px;
        height: 24px;

        .el-icon--left {
          font-size: 14px;
          margin-right: 4px;
          display: inline-flex;
          align-items: center;
        }

        span {
          display: inline-flex;
          align-items: center;
          height: 100%;
        }
      }
    }

    .pagination {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 32px;
      display: flex;
      justify-content: flex-end;
      padding: 8px 8px 8px 0;
      border-top: 1px solid var(--el-border-color-lighter);
      z-index: 1;

      :deep(.el-pagination) {
        .el-select .el-input {
          margin: 0;
        }

        .el-select__popper {
          margin-top: -4px;
        }

        .el-select-dropdown {
          margin-top: 0 !important;
        }
      }
    }

    :deep(.el-table) {
      border: none;
      margin-bottom: 0;

      .el-table__body-wrapper {
        overflow-y: auto;
      }

      // 固定列阴影
      .el-table__fixed-right::before,
      .el-table__fixed::before {
        display: none;
      }

      // 表头样式
      .el-table__header {
        th {
          background-color: var(--el-fill-color-darker);
          &.is-leaf {
            border-bottom: 1px solid var(--el-border-color-lighter);
          }
          .cell {
            font-weight: 600;
            color: var(--el-text-color-regular);
            font-size: 14px;
          }
        }
      }

      &::after {
        display: none;
      }

      .el-table__cell {
        border-bottom: 1px solid var(--el-border-color-lighter);
      }

      // 优化行样式
      .el-table__row {
        &:hover {
          background-color: var(--el-fill-color-light);
        }

        .el-table__cell {
          border-bottom: 1px solid var(--el-border-color-lighter);
        }
      }

      .el-button--link {
        height: auto;
        padding: 4px 8px;
        font-size: 14px;
        font-weight: normal;
      }
    }
  }
}
/* 新增全局样式（注意需要穿透scoped限制） */
:deep(.pagination-select-dropdown) {
  /* 强制弹窗向上展开 */
  top: auto !important;
  bottom: 100%;
  margin-bottom: 28px; /* 添加与分页器的间距 */

  /* 调整箭头方向 */
  .el-popper__arrow {
    top: 100%;
    bottom: auto;
    transform: translateY(-50%) rotate(180deg);
  }
}
</style>
